package com.adds.lvds.security.acegi.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.adds.lvds.core.utils.ApplicationContextUtils;
import com.adds.lvds.core.utils.PropertiesUtils;
import com.adds.lvds.security.model.SysResource;
import com.adds.lvds.security.model.SysRole;
import com.adds.lvds.security.service.SysResourceService;
import com.adds.lvds.security.service.SysRoleService;

public class MenuUtil {

	private static SysResourceService sysResourceService;

	private static SysRoleService sysRoleService;

	// 加载所有菜单
	private static List<SysResource> sysResources;

	// 加载所有角色，以及角色已授权菜单
	private static List<SysRole> sysRoles;

	public static void init() {
		sysResourceService = (SysResourceService) ApplicationContextUtils.getBean("sysResourceService");
		sysRoleService = (SysRoleService) ApplicationContextUtils.getBean("sysRoleService");
		reLoadMenu();
	}

	public static void reLoadMenu() {
		reLoadResource();
		reLoadRoles();
	}

	public static void reLoadResource() {
		sysResources = sysResourceService.queryAll(new SysResource());
	}

	public static void reLoadRoles() {
		Map<String, Object> map = new HashMap<>();
		sysRoles = sysRoleService.querySysRoleByMap(map);
	}

	public static void setSysResources(List<SysResource> sysResource) {
		sysResources = sysResource;
	}

	public static List<SysResource> getSysResources() {
		return sysResources;
	}

	public static void setSysRoles(List<SysRole> sysRole) {
		sysRoles = sysRole;
	}

	// 添加菜单
	public static void addSysResource(SysResource sysResource) {
		sysResources.add(sysResource);
	}

	// 添加角色
	public static void addSysRoles(SysRole sysRole) {
		sysRoles.add(sysRole);
	}

	public static void deleteSysRole(Integer roleId) {
		for (int i = 0; i < sysRoles.size(); i++) {
			if (sysRoles.get(i).getId() == roleId) {
				sysRoles.remove(i);
				break;
			}
		}
	}

	public static void deleteSysResource(Integer sysResId) {
		for (int i = 0; i < sysResources.size(); i++) {
			if (sysResources.get(i).getId() == sysResId) {
				sysResources.remove(i);
				break;
			}
		}
	}

	/**
	 * 添加角色权限
	 * 
	 * @param roleId
	 *            角色Id
	 * @param sysResourceList
	 *            授权菜单组
	 */
	public static void addSysRoleRes(Integer roleId, List<SysResource> sysResourceList) {
		for (int i = 0; i < sysRoles.size(); i++) {
			if (roleId == sysRoles.get(i).getId()) {
				sysRoles.get(i).setSysResources(sysResourceList);
				break;
			}
		}
	}

	// 获取角色全部权限
	public static List<SysResource> getAllSysResourcesByRoles(List<SysRole> roleList) {
		List<SysResource> sysResourceList = new ArrayList<SysResource>();

		List<SysResource> roleResources = null;
		if (roleList != null && roleList.size() > 0) {
			for (SysRole r : roleList) {
				SysRole role = getSysRoleById(String.valueOf(r.getId()));
				if (roleResources == null) {
					roleResources = role.getSysResources();
				} else {
					roleResources.addAll(role.getSysResources());
				}

			}

			if (roleResources != null && roleResources.size() > 0) {
				for (int i = roleResources.size() - 1; i > -1; i--) {
					for (int j = i - 1; j > -1; j--) {
						if (roleResources.get(i).getId() == roleResources.get(j).getId()) {
							roleResources.remove(i);
							break;
						}
					}
				}
			}

		}

		if (roleList == null) {
			sysResourceList = sysResources;
		} else if (roleResources != null && roleResources.size() > 0) {
			for (SysResource sysResource : roleResources) {
				for (SysResource resource : sysResources) {
					if (sysResource.getId() == resource.getId()) {
						sysResourceList.add(resource);
					}
				}
			}
		}

		return sysResourceList;
	}

	// 获取角色权限,返回父子菜单结构
	public static List<SysResource> getSysResourcesByRoles(List<SysRole> roleList) {
		List<SysResource> sysResourceList = new ArrayList<SysResource>();

		List<SysResource> roleResources = new ArrayList<SysResource>();
		if (roleList != null && roleList.size() > 0) {
			for (SysRole r : roleList) {
				SysRole role = getSysRoleById(String.valueOf(r.getId()));
				if (roleResources == null) {
					roleResources = role.getSysResources();
				} else {
					roleResources.addAll(role.getSysResources());
				}

			}

			if (roleResources != null && roleResources.size() > 0) {
				for (int i = roleResources.size() - 1; i > -1; i--) {
					for (int j = i - 1; j > -1; j--) {
						if (roleResources.get(i).getId() == roleResources.get(j).getId()) {
							roleResources.remove(i);
							break;
						}
					}
				}
			}
		}
		if (roleList == null) {
			roleResources = null;
		}
		sysResourceList = getSysRoleRes(roleResources);
		return sysResourceList;
	}

	public static SysRole getSysRoleById(String roleId) {

		if (roleId == null || roleId.trim().length() == 0)
			return null;

		SysRole sysRole = null;

		for (SysRole role : sysRoles) {
			if (role.getId() == Integer.parseInt(roleId)) {
				sysRole = role;
				break;
			}
		}

		return sysRole;
	}

	public static List<SysResource> getSysRoleRes(List<SysResource> roleResources) {
		List<SysResource> sysResourceList = new ArrayList<SysResource>();

		// List<SysResource>
		// roleResources=role==null?null:role.getSysResources();
		// 获取一级目录
		for (SysResource sysResource : sysResources) {
			if (roleResources != null) {
				for (SysResource resource : roleResources) {
					if (resource != null) {
						if (sysResource.getParentId() == 0 && sysResource.getId() == resource.getId()) {
							sysResourceList.add(sysResource);
						}
					}
				}
			} else {
				if (sysResource.getParentId() == 0) {
					sysResourceList.add(sysResource);
				}
			}

		}

		HashMap<Integer, List<SysResource>> childHashMap = getSysResourceChild(sysResourceList, roleResources);

		if (childHashMap != null) {
			for (int i = 0; i < sysResourceList.size(); i++) {
				for (Integer resId : childHashMap.keySet()) {
					if (sysResourceList.get(i).getId() == resId) {
						sysResourceList.get(i).setChildren(childHashMap.get(resId));
						break;
					}
				}
			}
		}

		return sysResourceList;
	}

	public static HashMap<Integer, List<SysResource>> getSysResourceChild(List<SysResource> sysResourceList,
			List<SysResource> roleResourceList) {
		HashMap<Integer, List<SysResource>> hashMap = null;

		for (SysResource sysResource : sysResourceList) {
			List<SysResource> list = new ArrayList<SysResource>();
			for (SysResource resource : sysResources) {
				if (roleResourceList != null) {
					for (SysResource res : roleResourceList) {
						/*
						 * System.out.println("sysResource.getId()---"+sysResource
						 * .getId()+"---resource.getParentId()-----"+resource. getParentId
						 * ()+"----resource.getId()----"+resource.getId
						 * ()+"---res.getId()-----"+res.getId());
						 */
						if ((sysResource.getId().intValue() == resource.getParentId().intValue())
								&& resource.getId().intValue() == res.getId().intValue()) {
							if (hashMap == null) {
								hashMap = new HashMap<Integer, List<SysResource>>();
							}

							list.add(resource);
						}
					}
				} else {
					if (sysResource.getId().intValue() == resource.getParentId().intValue()) {
						if (hashMap == null) {
							hashMap = new HashMap<Integer, List<SysResource>>();
						}

						list.add(resource);
					}
				}

			}
			if (list.size() > 0) {
				HashMap<Integer, List<SysResource>> childHashMap = getSysResourceChild(list, roleResourceList);
				if (childHashMap != null) {
					for (int i = 0; i < list.size(); i++) {
						for (Integer resId : childHashMap.keySet()) {
							if (list.get(i).getId() == resId) {
								list.get(i).setChildren(childHashMap.get(resId));
								break;
							}
						}
					}
				}
				hashMap.put(sysResource.getId(), list);
			}

		}

		return hashMap;
	}

	/**
	 * 菜单加载主方法
	 * 
	 * @param request
	 * @return
	 */
	public static String getSysResourcesHtml(HttpServletRequest request) {
		// reLoadMenu();
		Map<String, Object> map = new HashMap<>();

		List<SysResource> rs = null;
		// 如果管理员是admin 获取所有的资源数据
		if (PropertiesUtils.findPropertiesKey("rootName").equals(CurrentUserUtils.currentUser(request).getUserName())) {
			map.put("role_id", CurrentUserUtils.currentUser(request).getRoleList().get(0).getId());
			map.put("type", 1);
			rs = sysResourceService.querySysResourceByMap(map);
		} else {
			map.put("role_id", CurrentUserUtils.currentUser(request).getRoleList().get(0).getId());
			map.put("type", 1);
			rs = sysResourceService.querySysResourceByMap(map);
		}
		String ctx = request.getContextPath();
		StringBuffer strHtml = new StringBuffer();

		for (SysResource sysResource : rs) {
			// 菜单html格式输出
			strHtml.append(getSysResourceHtml(sysResource, ctx, 0));
		}
		//System.out.println(strHtml.toString());
		return strHtml.toString();
	}

	/**
	 * 菜单html拼接
	 * 
	 * @param sysResource
	 * @param ctx
	 * @param flag
	 * @return
	 */
	public static String getSysResourceHtml(SysResource sysResource, String ctx, int flag) {
		StringBuffer strHtml = new StringBuffer();

		if ("1".equals(sysResource.getType())) {
			strHtml.append("<li>");
			if (StringUtils.isNotEmpty(sysResource.getResUrl())) {
				strHtml.append("<a class='J_menuItem' href='" + ctx + sysResource.getResUrl() + "'>");
			} else {
				strHtml.append("<a href='#'>");
			}

			if (sysResource.getImg() != null && sysResource.getImg().trim().length() > 0) {
				strHtml.append("<i class='" + sysResource.getImg() + "'></i>");
			}
			strHtml.append(
					"<span class='nav-label'>" + sysResource.getName() + "</span>");

			if (sysResource.getChildren() != null && sysResource.getChildren().size() > 0) {
				strHtml.append("<span class='fa arrow'></span></a>");
				strHtml.append("<ul class='nav nav-second-level'>");
				for (SysResource resource : sysResource.getChildren()) {
					strHtml.append("<li>");
					if (StringUtils.isNotEmpty(resource.getResUrl())) {
						strHtml.append("<a class='J_menuItem' href='" + ctx + resource.getResUrl() + "'>");
					} else {
						strHtml.append("<a href='#'>");
					}

					if (resource.getImg() != null && resource.getImg().trim().length() > 0) {
						strHtml.append("<i class='" + resource.getImg() + "'></i>" + resource.getName());
					}
					Map<String, Object> maps = new HashMap<>();
					maps.put("parentid", resource.getId());
					maps.put("role_id",sysResource.getRole_id());
					List<SysResource> list_1 = sysResourceService.querySysResourceByMap(maps);
					if (list_1 != null && list_1.size() > 0) {
						String rHtml = childHtml(list_1, ctx);
						strHtml.append(rHtml);
						strHtml.append("</li>");
					} else {
						strHtml.append("<span class='nav-label'></span></a>");
						strHtml.append("</li>");
					}
				}
				strHtml.append("</ul>");
			}else {
				strHtml.append("</a>");
			}
		}
		strHtml.append("</li>");

		return strHtml.toString();
	}

	public static String childHtml(List<SysResource> list, String ctx) {
		StringBuffer strHtml = new StringBuffer();
		strHtml.append("<span class='fa arrow'></span></a>");
		strHtml.append("<ul class='nav nav-third-level'><li>");
		for (SysResource sysResource : list) {
			if (StringUtils.isNotEmpty(sysResource.getResUrl())) {
				strHtml.append("<a class='J_menuItem' href='" + ctx + sysResource.getResUrl() + "'>");
			} else {
				strHtml.append("<a href='#'>");
			}
			if (sysResource.getImg() != null && sysResource.getImg().trim().length() > 0) {
				strHtml.append("<i class='" + sysResource.getImg() + "'></i>" + sysResource.getName());
			}
			if (sysResource.getChildren() != null && sysResource.getChildren().size() > 0) {
				strHtml.append("<span class='fa arrow'></span></a>");
				strHtml.append("<ul class='nav nav-fore-level'><li>");
				for (SysResource sysResource1 : sysResource.getChildren()) {
					if (StringUtils.isNotEmpty(sysResource1.getResUrl())) {
						strHtml.append("<a class='J_menuItem' href='" + ctx + sysResource1.getResUrl() + "'>");
					} else {
						strHtml.append("<a href='#'>");
					}
					if (sysResource1.getImg() != null && sysResource1.getImg().trim().length() > 0) {
						strHtml.append("<i class='" + sysResource1.getImg() + "'></i>" + sysResource1.getName());
					}

				}
				strHtml.append("</a></li></ul>");
			}

		}
		strHtml.append("</a></li></ul>");
		return strHtml.toString();
	}

	public static String getMenuChildBut(List<SysRole> roleList, String requestUrl) {
		String childButHtml = "";
		List<SysResource> sysResourceList = getAllSysResourcesByRoles(roleList);
		if (requestUrl.indexOf("?") > -1) {
			requestUrl = requestUrl.substring(0, requestUrl.indexOf("?"));
		}

		int menuId = 0;

		for (SysResource sysResource : sysResourceList) {
			if (requestUrl.equals(sysResource.getResUrl())) {
				if ("2".equals(sysResource.getType())) {
					menuId = sysResource.getId();
				}
				break;
			}
		}
		if (menuId != 0) {
			List<SysResource> childBut = new ArrayList<SysResource>();
			for (SysResource sysResource : sysResourceList) {
				if (sysResource.getParentId() == menuId && "3".equals(sysResource.getType())) {
					childBut.add(sysResource);
				}
			}

			childButHtml = getButHtmlBySysResources(childBut);

		}
		return childButHtml;
	}

	public static String getButHtmlBySysResources(List<SysResource> butSysResources) {
		StringBuffer butHtml = new StringBuffer();
		for (SysResource sysResource : butSysResources) {
			butHtml.append("<button class='btn btn-success btn-outline' type='button' id='" + sysResource.getResKey()
					+ "' fromUrl='" + sysResource.getResUrl() + "'>");
			if (sysResource.getImg() != null && sysResource.getImg().trim().length() > 0) {
				butHtml.append("<i class='" + sysResource.getImg() + "'></i>");
			}
			butHtml.append(" " + sysResource.getName());
			butHtml.append("</button> ");
		}
		return butHtml.toString();
	}

}